<template>
  <div>
    <SearchContainer @search="getDataSource" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="mcbm" label="" class="">
          <a-input v-model:value="formState.mcbm" class="w-64" placeholder="单号/供应商名称" />
        </a-form-item>
        <a-form-item name="dateRange" label="日期范围">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" value-format="YYYY-MM-DD" />
        </a-form-item>

        <a-form-item name="zjm" label="" class="ml-8">
          <a-input v-model:value="formState.zjm" class="w-64" placeholder="物品编号/物品名称/助记码" />
        </a-form-item>
        <a-form-item label="状态" name="status" class="w-64">
          <a-select v-model:value="formState.status" placeholder="请选择" allow-clear>
            <a-select-option :value="0">待确认</a-select-option>
            <a-select-option :value="1">已确认</a-select-option>
            <a-select-option :value="2">已作废</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex justify-start">
        <a-button class="mb-2" type="primary" @click="onAdd"> 新增 </a-button>
      </div>
      <BaseTable
        fill
        :data-source="dataSource"
        :expanded-row-keys="expandedRowKeys"
        :loading="loading"
        column-code="00001084"
        :extra-height="50"
        :scroll="{ x: 1900 }"
        :pagination="{ total: page.total, current: page.current, pageSize: page.pageSize }"
        @change="onPageChange"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'thdh'">
            <PopoverTable :config="detailConfig" :params="{ thdh: record.thdh }" :width="1800">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'ypmc'">
                  <MedicineInfo :value="{ mc: popRecord.ypmc, gg: popRecord.gg, cj: popRecord.cj }" />
                </template>
              </template>
              {{ record.thdh }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="record.status === 0" color="blue">待确认</a-tag>
            <a-tag v-if="record.status === 1" color="green">已确认</a-tag>
            <a-tag v-if="record.status === 2" color="red">已作废</a-tag>
          </template>
          <template v-if="column.dataIndex === 'fpzt'">
            <a-tag v-if="record.fpzt === 0" color="green">普通</a-tag>
            <a-tag v-if="record.fpzt === 1" color="blue">在途</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" :disabled="record.status === 1" @click="onDetail(record)">明细</a-button>
              <BaseButton confirm-text="确认退货?" type="link" size="small" :disabled="record.status === 1" @click="onConfirm(record)">确认退货</BaseButton>
              <a-button type="link" size="small" @click="onPrint(record)"> 打印 </a-button>
              <TableMoreButton>
                <a-button type="link" size="small" :disabled="record.status === 1" @click="onEdit(record)">修改</a-button>
                <BaseButton
                  confirm-text="是否作废此退货单?"
                  type="text"
                  danger
                  size="small"
                  :disabled="record.status === 1 || record.status === 2"
                  @click="onClickCancel(record)"
                >
                  作废
                </BaseButton>
              </TableMoreButton>
            </a-space>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="column in columnsData" :key="column.dataIndex">
                <a-table-summary-cell v-if="column.dataIndex === 'NO'"> 合计 </a-table-summary-cell>
                <a-table-summary-cell v-else-if="!column.isHide">
                  <div :class="bottomTotal[column.dataIndex] ? 'text-right' : 'text-center'">{{ bottomTotal[column.dataIndex] || '-' }}</div>
                </a-table-summary-cell>
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </BaseTable>
    </a-card>
    <Edit v-model:open="open" :row-data="rowData" @ok="getDataSource" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { formatAmount } from '@/utils/format.js'
import SearchContainer from '@/components/SearchContainer'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import useUserStore from '@/store/user'
import Edit from './Edit'

const router = useRouter()
const { empName } = useUserStore()
const page = ref({
  total: 0,
  current: 1,
  pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
})
const rowData = ref(null)
const formRef = ref(null)
const dataSource = ref([])

const expandedRowKeys = ref([])
const open = ref(false)
const loading = ref(false)
const formState = ref({
  status: null,
  dateRange: [dayjs(new Date().setDate(new Date().getDate() - 10)).format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  pxlx: '',
  pxzd: ''
})

const detailConfig = ref({
  url: '/oos/psiform/getreturnOrderDetailList',
  columnCode: '000145',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})

const onDetail = (record) => {
  router.push({
    path: '/optic-warehouse/warehouse/return-detail',
    query: {
      thdh: record.thdh
    }
  })
}
const onClickCancel = async (record) => {
  const { code, msg } = await post('oos/psiform/doCancelReturnHead', {
    thdh: record.thdh
  })
  if (code !== 0) return message.error(msg || '作废失败')
  getDataSource()
  message.success('作废成功')
}
const onEdit = (record) => {
  rowData.value = Object.assign({}, record)
  open.value = true
}
const onAdd = () => {
  rowData.value = null
  open.value = true
}
const bottomTotal = ref({})
const getDataSource = async () => {
  loading.value = true
  const { dateRange, ...rest } = formState.value
  const { data, code, total } = await post('/oos/psiform/getReturnOrderList', {
    ...rest,
    pageNum: page.value.current,
    pageSize: page.value.pageSize,
    stdate: dateRange?.[0],
    eddate: dateRange?.[1]
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    page.value.total = total
    if (dataSource.value.length > 0) {
      bottomTotal.value.hjsl = dataSource.value[0].slhj
      bottomTotal.value.hjje = formatAmount(dataSource.value[0].hjjezhj)
    }
  }
}

const onConfirm = async (record) => {
  const { code } = await post('/oos/psiform/doConfirmReturnOrder', {
    dh: record.thdh,
    qrr: empName
  })
  if (code === 0) {
    getDataSource()
    message.success('确认成功')
  } else {
    message.error('确认失败')
  }
}
const onPageChange = ({ current, pageSize }, filters, sorter) => {
  page.value.current = current
  page.value.pageSize = pageSize
  if (sorter.column?.dataIndex) {
    formState.value.pxlx = sorter.order === 'ascend' ? '1' : '2'
    if (sorter.column.dataIndex === 'thdh') {
      formState.value.pxzd = '1'
    } else if (sorter.column.dataIndex === 'qrsj') {
      formState.value.pxzd = '2'
    } else {
      formState.value.pxzd = '3'
    }
  } else {
    formState.value.pxlx = ''
  }
  getDataSource()
}
//获取表头
const columnsData = ref([])
const getTableColumns = async () => {
  const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: '00001084' })
  if (code !== 0) return message.error(code)
  columnsData.value = data
}

const onPrint = async (row) => {
  const { code, msg, data } = await post('/oos/psiform/printMtrKcThdzbList', { thdh: row.thdh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

onMounted(() => {
  getDataSource()
  getTableColumns()
})
</script>
